'''
Author: 红色梧桐 940120450@qq.com
Date: 2024-09-02 21:06:34
LastEditors: 红色梧桐 940120450@qq.com
LastEditTime: 2024-09-05 20:46:57
FilePath: \myReader\applications\services\wx.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from datetime import datetime
import json
import time
import logging
from applications.configs.func import parse_time_strings
from applications.extends.wxUtils import wxUtils
from applications.extends.cacheUtils.redis import redis_client
from applications.models import Session
from applications.models.wx import WxMessage

logger = logging.getLogger(__name__)


wx = wxUtils()
wx.close_form()

# 获取微信消息
def start_wechat_task_func():
    wx_name = wx.get_wx_id()
    print(wx_name, "微信消息获取任务启动", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # 获取最新的消息
    messages = wx.GetAllNewMessage()
    for key, value in messages.items():
        # 系统消息不处理
        if value[0] == "SYS":
            continue

        # 时间消息
        time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if value[0] == "TIME":
            time_str = parse_time_strings(value[1])

        # 解析其他信息
        for m in value:
            print(key, value, m)
            msg = json.dumps({"wx_id": wx_name, 'create_time': time_str, "users": key, "message": {"send": m[0], "content": m[1]}}, ensure_ascii=False)
            redis_client.lpush("wechat_message", msg)

    wx.close_form()

# 将消息写入mysql
def write_wx_message_to_mysql():
    print("微信消息写入mysql任务启动", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    while True:
        message = redis_client.rpop("wechat_message")
        if message:
            session = Session()
            try:
                data = json.loads(message.encode("utf-8"))
                message = data["message"]
                wx_id = data["wx_id"] if 'wx_id' in data else wx.get_wx_id()
                create_time = data["create_time"] if 'create_time' in data else datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                msg = WxMessage(wx_id=wx_id, user=data["users"], message=message["content"], send_user=message["send"], create_time=create_time)
                session.add(msg)
                session.commit()
            except Exception as e:
                logger.info("微信消息写入mysql任务异常: {}, {}".format(e, message.encode("utf-8")))
                session.rollback()
            finally:
                session.close()

        time.sleep(1)